﻿using huaxin_Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace huaxin_core
{
    public class LuckDrawHelp
    {


        private static Random rnd = new Random();

        /// <summary>
        /// 获取抽奖结果
        /// </summary>
        /// <param name="prob"></param>
        /// <returns></returns>
        private static int GetLuckdrawResult(double[] prob)
        {
            int resultInt = 0;
            int n = (int)(prob.Sum() * 1000);           //计算概率总和，放大1000倍
            Random r = rnd;
            float x = (float)r.Next(0, n) / 1000;       //随机生成0~概率总和的数字

            double pre = 0.0;
            double next = 0.0;

            for (int i = 0; i < prob.Count(); i++)
            {
                pre = prob.Take(i).Sum();         //区间下界
                next = prob.Take(i + 1).Sum();    //区间上界
                if (x >= pre && x < next)               //如果在该区间范围内，就返回结果退出循环
                {
                    resultInt = i;
                    break;
                }
            }

            return resultInt;
        }


        /// <summary>
        /// 开始抽奖
        /// </summary>
        /// <param name="luckdraws"></param>
        /// <returns></returns>
        public static huaxin_commodity SendLuckdraw(List<huaxin_luckdraw> luckdraws)
        {

            if (luckdraws == null && luckdraws.Count == 0)
                return new huaxin_commodity();

            //概率
            double[] probabilityArray = luckdraws.Select(i => i.Probability).ToArray();

            //抽奖结果
            var num = GetLuckdrawResult(probabilityArray);


            return GetCommodityModel(num,luckdraws);
        }

        /// <summary>
        /// 抽奖后返回奖品名称和权重
        /// </summary>
        /// <param name="num"></param>
        /// <param name="luckdraws"></param>
        /// <returns></returns>
        private static huaxin_commodity GetCommodityModel(int num, List<huaxin_luckdraw> luckdraws)
        {

            huaxin_commodity model = new huaxin_commodity();
            var luckdraw = luckdraws[num];
            model.PrizeId = luckdraw.Id;
            model.PrizeName = luckdraw.Name;

            switch (num)
            {
                case 1:
                    model.Angle = 26;
                    break;
                case 2:
                    model.Angle = 282;
                    break;
                case 3:
                    model.Angle = 185;
                    break;
                case 4:
                    model.Angle = 137;
                    break;
                case 5:
                    model.Angle = 337;
                    break;
                case 6:
                    model.Angle = 235;
                    break;
                case 7:
                    model.Angle = 88;
                    break;
            }

            return model;
        }

    }
}
